<template>
  <div class="recipe-detail-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      :title="recipe.name"
      left-arrow
      fixed
      @click-left="$router.back()"
    />
    <div class="nav-placeholder"></div>

    <!-- 加载中 -->
    <template v-if="loading">
      <div class="loading-container">
        <van-loading type="spinner" size="36px">加载中...</van-loading>
      </div>
    </template>

    <!-- 食谱详情内容 -->
    <template v-else>
      <!-- 食谱封面图 -->
      <div class="recipe-cover">
        <van-image width="100%" height="220" :src="recipe.image" fit="cover" />
        <div class="recipe-actions">
          <div class="action-btn" @click="toggleFavorite">
            <van-icon
              :name="isFavorite ? 'star' : 'star-o'"
              :color="isFavorite ? '#ff9800' : '#fff'"
              size="24"
            />
          </div>
          <div class="action-btn" @click="showShareOptions">
            <van-icon name="share-o" color="#fff" size="24" />
          </div>
        </div>
      </div>

      <!-- 食谱标题和评分 -->
      <div class="recipe-header">
        <h1 class="recipe-title">{{ recipe.name }}</h1>
        <div class="recipe-rating">
          <van-rate v-model="recipe.rating" readonly allow-half />
          <span class="rating-count">({{ recipe.ratingCount }}人评分)</span>
        </div>
        <div class="recipe-meta">
          <div class="meta-item">
            <van-icon name="underway-o" />
            <span>{{ recipe.cookTime }}分钟</span>
          </div>
          <div class="meta-item">
            <van-icon name="fire-o" />
            <span>{{ recipe.calories }}千卡</span>
          </div>
          <div class="meta-item">
            <van-icon name="guide-o" />
            <span>{{ getDifficultyText(recipe.difficulty) }}</span>
          </div>
        </div>
        <div class="recipe-tags">
          <van-tag
            v-for="tag in recipe.tags"
            :key="tag"
            plain
            type="primary"
            size="medium"
            style="margin-right: 8px"
          >
            {{ tag }}
          </van-tag>
        </div>
      </div>

      <!-- 食谱信息Tab页 -->
      <van-tabs v-model:active="activeTab" sticky swipeable>
        <!-- 食材配料 -->
        <van-tab title="食材">
          <div class="tab-content">
            <div class="ingredients-section">
              <h3 class="section-title">
                主料 <span class="servings">({{ recipe.servings }}人份)</span>
              </h3>
              <van-cell-group inset>
                <van-cell
                  v-for="ingredient in recipe.mainIngredients"
                  :key="ingredient.id"
                  :title="ingredient.name"
                  :value="ingredient.amount"
                  @click="navigateToIngredient(ingredient.id)"
                />
              </van-cell-group>

              <h3
                class="section-title"
                v-if="
                  recipe.secondaryIngredients &&
                  recipe.secondaryIngredients.length > 0
                "
              >
                辅料
              </h3>
              <van-cell-group
                inset
                v-if="
                  recipe.secondaryIngredients &&
                  recipe.secondaryIngredients.length > 0
                "
              >
                <van-cell
                  v-for="ingredient in recipe.secondaryIngredients"
                  :key="ingredient.id"
                  :title="ingredient.name"
                  :value="ingredient.amount"
                  @click="navigateToIngredient(ingredient.id)"
                />
              </van-cell-group>
            </div>
          </div>
        </van-tab>

        <!-- 烹饪步骤 -->
        <van-tab title="做法">
          <div class="tab-content">
            <div class="steps-section">
              <van-steps direction="vertical" :active="recipe.steps.length">
                <van-step v-for="(step, index) in recipe.steps" :key="index">
                  <h3>步骤 {{ index + 1 }}</h3>
                  <div class="step-content">
                    <van-image
                      v-if="step.image"
                      width="100"
                      height="80"
                      :src="step.image"
                      fit="cover"
                      radius="4"
                    />
                    <p>{{ step.description }}</p>
                  </div>
                </van-step>
              </van-steps>
            </div>
          </div>
        </van-tab>

        <!-- 营养信息 -->
        <van-tab title="营养">
          <div class="tab-content">
            <div class="nutrition-section">
              <h3 class="section-title">
                营养成分表 <span class="per-serving">(每100克)</span>
              </h3>

              <div class="nutrition-pie-chart">
                <!-- 这里可以添加营养成分比例图表 -->
                <div class="pie-chart-placeholder">营养成分比例图</div>
              </div>

              <van-cell-group inset>
                <van-cell
                  title="热量"
                  :value="`${recipe.nutrition.calories} 千卡`"
                />
                <van-cell
                  title="蛋白质"
                  :value="`${recipe.nutrition.protein}克`"
                />
                <van-cell title="脂肪" :value="`${recipe.nutrition.fat}克`" />
                <van-cell
                  title="碳水化合物"
                  :value="`${recipe.nutrition.carbs}克`"
                />
                <van-cell
                  title="膳食纤维"
                  :value="`${recipe.nutrition.fiber}克`"
                />
                <van-cell title="糖" :value="`${recipe.nutrition.sugar}克`" />
                <van-cell
                  title="钠"
                  :value="`${recipe.nutrition.sodium}毫克`"
                />
              </van-cell-group>
            </div>
          </div>
        </van-tab>

        <!-- 健康分析 -->
        <van-tab title="点评">
          <div class="tab-content">
            <div class="health-section">
              <h3 class="section-title">营养师点评</h3>
              <div class="health-comments">
                <p>
                  {{
                    recipe.healthComment ||
                    "这道菜营养均衡，适合大多数人食用。建议晚餐享用，搭配一些新鲜蔬果。"
                  }}
                </p>
              </div>

              <h3 class="section-title">适宜人群</h3>
              <div class="suitable-for">
                <van-tag
                  v-for="item in recipe.suitableFor"
                  :key="item"
                  plain
                  type="success"
                  size="medium"
                  style="margin-right: 8px; margin-bottom: 8px"
                >
                  {{ item }}
                </van-tag>
              </div>

              <h3 class="section-title">不适宜人群</h3>
              <div class="not-suitable-for">
                <van-tag
                  v-for="item in recipe.notSuitableFor"
                  :key="item"
                  plain
                  type="danger"
                  size="medium"
                  style="margin-right: 8px; margin-bottom: 8px"
                >
                  {{ item }}
                </van-tag>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>

      <!-- 评分和评论 -->
      <div class="comments-section">
        <h3 class="section-title">用户评价 ({{ recipe.comments.length }})</h3>
        <div class="user-rating" v-if="!hasRated">
          <div class="rate-title">为这道菜评分:</div>
          <van-rate v-model="userRating" @change="submitRating" />
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <van-empty
            description="暂无评论"
            v-if="recipe.comments.length === 0"
          />
          <div
            v-else
            class="comment-item"
            v-for="comment in recipe.comments"
            :key="comment.id"
          >
            <div class="comment-header">
              <div class="user-info">
                <van-image
                  round
                  width="40"
                  height="40"
                  :src="comment.userAvatar"
                  fit="cover"
                />
                <div class="user-details">
                  <div class="user-name">{{ comment.userName }}</div>
                  <div class="comment-time">
                    {{ formatDate(comment.createdAt) }}
                  </div>
                </div>
              </div>
              <van-rate
                v-model="comment.rating"
                readonly
                allow-half
                size="12"
              />
            </div>
            <div class="comment-content">
              {{ comment.content }}
            </div>
            <div
              class="comment-images"
              v-if="comment.images && comment.images.length > 0"
            >
              <van-image
                v-for="(image, index) in comment.images"
                :key="index"
                width="80"
                height="80"
                :src="image"
                fit="cover"
                radius="4"
                style="margin-right: 8px"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 相关食谱推荐 -->
      <div class="related-recipes">
        <h3 class="section-title">你可能也喜欢</h3>
        <div class="recipes-scroll">
          <div
            v-for="relatedRecipe in relatedRecipes"
            :key="relatedRecipe.id"
            class="related-recipe-card"
            @click="navigateToRecipe(relatedRecipe.id)"
          >
            <van-image
              :src="relatedRecipe.image"
              width="120"
              height="80"
              fit="cover"
              radius="4"
            />
            <div class="related-recipe-name">{{ relatedRecipe.name }}</div>
          </div>
        </div>
      </div>
    </template>

    <!-- 分享选项弹出层 -->
    <van-share-sheet
      v-model:show="showShare"
      title="分享给好友"
      :options="shareOptions"
      @select="onShareSelect"
    />

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <van-button
        type="primary"
        size="large"
        icon="good-job-o"
        @click="showReviewForm"
        >我做过了</van-button
      >
    </div>

    <!-- 食谱评价表单弹窗 -->
    <van-dialog
      v-model:show="showReview"
      title="分享你的烹饪体验"
      show-cancel-button
      @confirm="submitReview"
    >
      <div class="review-form">
        <div class="rating-area">
          <div class="rate-title">为这道菜评分:</div>
          <van-rate v-model="reviewForm.rating" />
        </div>
        <van-field
          v-model="reviewForm.content"
          label="评价"
          type="textarea"
          placeholder="分享你的烹饪体验和建议..."
          rows="3"
          autosize
        />
        <div class="upload-area">
          <div class="upload-title">上传美食照片:</div>
          <van-uploader v-model="reviewForm.images" multiple max-count="3" />
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast, showSuccessToast } from "vant";
import { useUserStore } from "@/stores/userStore";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 状态变量
const loading = ref(true);
const activeTab = ref(0);
const isFavorite = ref(false);
const hasRated = ref(false);
const userRating = ref(0);
const showShare = ref(false);
const showReview = ref(false);

// 食谱数据
const recipe = ref({});
const relatedRecipes = ref([]);

// 评价表单
const reviewForm = reactive({
  rating: 5,
  content: "",
  images: [],
});

// 分享选项
const shareOptions = [
  { name: "微信", icon: "wechat" },
  { name: "微博", icon: "weibo" },
  { name: "复制链接", icon: "link" },
  { name: "分享图片", icon: "photo" },
  { name: "二维码", icon: "qrcode" },
];

// 获取食谱详情（模拟API调用）
const fetchRecipeDetail = async (id) => {
  loading.value = true;
  try {
    // 这里应该是真实的API调用
    console.log(`获取食谱详情，ID: ${id}`);

    // 模拟API延迟
    await new Promise((resolve) => setTimeout(resolve, 800));

    // 模拟数据
    recipe.value = {
      id: id,
      name: "健康蔬菜沙拉",
      image: "https://img01.yzcdn.cn/vant/cat.jpeg",
      description:
        "这是一道低脂健康的蔬菜沙拉，富含多种维生素和矿物质，是减肥和健康饮食的理想选择。",
      cookTime: 15,
      prepTime: 10,
      servings: 2,
      calories: 320,
      difficulty: 1, // 1: 简单, 2: 中等, 3: 困难
      rating: 4.5,
      ratingCount: 128,
      tags: ["健康", "低脂", "沙拉", "素食"],
      mainIngredients: [
        { id: 1, name: "生菜", amount: "100克" },
        { id: 2, name: "小番茄", amount: "50克" },
        { id: 3, name: "黄瓜", amount: "1根" },
        { id: 4, name: "牛油果", amount: "1个" },
      ],
      secondaryIngredients: [
        { id: 5, name: "橄榄油", amount: "1勺" },
        { id: 6, name: "柠檬汁", amount: "1勺" },
        { id: 7, name: "盐", amount: "少许" },
        { id: 8, name: "黑胡椒", amount: "少许" },
      ],
      steps: [
        {
          description: "将生菜洗净，撕成小块，放入大碗中",
          image: "https://img01.yzcdn.cn/vant/cat.jpeg",
        },
        {
          description: "小番茄洗净，切成两半，加入碗中",
          image: "https://img01.yzcdn.cn/vant/cat.jpeg",
        },
        {
          description: "黄瓜洗净，切成薄片，加入碗中",
          image: "https://img01.yzcdn.cn/vant/cat.jpeg",
        },
        {
          description: "牛油果切开，去核，切成小块，加入碗中",
          image: "https://img01.yzcdn.cn/vant/cat.jpeg",
        },
        {
          description: "加入橄榄油、柠檬汁、盐和黑胡椒，轻轻拌匀即可",
          image: "https://img01.yzcdn.cn/vant/cat.jpeg",
        },
      ],
      nutrition: {
        calories: 320,
        protein: 5,
        fat: 28,
        carbs: 12,
        fiber: 7,
        sugar: 3,
        sodium: 120,
      },
      healthComment:
        "这道沙拉营养均衡，富含不饱和脂肪酸、膳食纤维和多种维生素，是一道健康的轻食选择。牛油果中的脂肪是健康脂肪，有助于降低坏胆固醇。",
      suitableFor: ["减肥人群", "素食主义者", "高血压人群", "糖尿病人群"],
      notSuitableFor: ["牛油果过敏者"],
      comments: [
        {
          id: 1,
          userName: "健康达人",
          userAvatar: "https://img01.yzcdn.cn/vant/cat.jpeg",
          rating: 5,
          content: "非常美味且健康的沙拉，我已经连续做了一周了！推荐大家尝试！",
          images: ["https://img01.yzcdn.cn/vant/cat.jpeg"],
          createdAt: new Date(Date.now() - 864000000), // 10天前
        },
        {
          id: 2,
          userName: "美食爱好者",
          userAvatar: "https://img01.yzcdn.cn/vant/cat.jpeg",
          rating: 4,
          content: "加了一些核桃和蓝莓，味道更丰富了！",
          images: [],
          createdAt: new Date(Date.now() - 345600000), // 4天前
        },
      ],
    };

    // 模拟相关食谱
    relatedRecipes.value = [
      {
        id: 101,
        name: "意式蔬菜沙拉",
        image: "https://img01.yzcdn.cn/vant/cat.jpeg",
      },
      {
        id: 102,
        name: "鲜果沙拉",
        image: "https://img01.yzcdn.cn/vant/cat.jpeg",
      },
      {
        id: 103,
        name: "藜麦沙拉",
        image: "https://img01.yzcdn.cn/vant/cat.jpeg",
      },
      {
        id: 104,
        name: "鸡肉凯撒沙拉",
        image: "https://img01.yzcdn.cn/vant/cat.jpeg",
      },
    ];

    // 模拟收藏状态
    isFavorite.value = Math.random() > 0.5;

    // 模拟评分状态
    hasRated.value = Math.random() > 0.7;
    if (hasRated.value) {
      userRating.value = Math.floor(Math.random() * 3) + 3; // 3-5分
    }
  } catch (error) {
    console.error("获取食谱详情失败", error);
    showToast("获取食谱详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取难度文本
const getDifficultyText = (level) => {
  const texts = ["", "简单", "中等", "困难"];
  return texts[level] || "";
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "";

  const now = new Date();
  const diff = now - new Date(date);

  // 小于1小时
  if (diff < 3600000) {
    return "刚刚";
  }
  // 小于24小时
  else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }
  // 小于30天
  else if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`;
  }
  // 其他
  else {
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
      2,
      "0"
    )}-${String(d.getDate()).padStart(2, "0")}`;
  }
};

// 收藏/取消收藏
const toggleFavorite = async () => {
  try {
    // 这里应该是真实的API调用
    console.log(
      `${isFavorite.value ? "取消收藏" : "收藏"}食谱，ID: ${recipe.value.id}`
    );

    // 模拟API延迟
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 更新状态
    isFavorite.value = !isFavorite.value;
    showToast(isFavorite.value ? "已收藏" : "已取消收藏");
  } catch (error) {
    console.error("操作失败", error);
    showToast("操作失败，请稍后再试");
  }
};

// 提交评分
const submitRating = async (value) => {
  if (!userStore.isLoggedIn) {
    showToast("请先登录");
    router.push("/login");
    return;
  }

  try {
    // 这里应该是真实的API调用
    console.log(`提交评分，ID: ${recipe.value.id}, 分数: ${value}`);

    // 模拟API延迟
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 更新状态
    hasRated.value = true;
    showSuccessToast("评分成功！");
  } catch (error) {
    console.error("评分失败", error);
    showToast("评分失败，请稍后再试");
  }
};

// 显示分享选项
const showShareOptions = () => {
  showShare.value = true;
};

// 分享选择处理
const onShareSelect = (option) => {
  showToast(`已${option.name}`);
  showShare.value = false;
};

// 显示评价表单
const showReviewForm = () => {
  if (!userStore.isLoggedIn) {
    showToast("请先登录");
    router.push("/login");
    return;
  }
  showReview.value = true;
};

// 提交评价
const submitReview = async () => {
  try {
    // 这里应该是真实的API调用
    console.log("提交评价", {
      recipeId: recipe.value.id,
      rating: reviewForm.rating,
      content: reviewForm.content,
      images: reviewForm.images,
    });

    // 模拟API延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 重置表单
    reviewForm.rating = 5;
    reviewForm.content = "";
    reviewForm.images = [];

    // 更新状态
    hasRated.value = true;
    userRating.value = reviewForm.rating;

    // 刷新评论列表
    fetchRecipeDetail(recipe.value.id);

    showSuccessToast("评价成功！");
  } catch (error) {
    console.error("评价失败", error);
    showToast("评价失败，请稍后再试");
  }
};

// 导航到食谱详情
const navigateToRecipe = (id) => {
  router.push(`/recipe/${id}`);
};

// 导航到食材详情
const navigateToIngredient = (id) => {
  router.push(`/food/${id}`);
};

// 初始化
onMounted(() => {
  const id = route.params.id;
  if (id) {
    fetchRecipeDetail(id);
  } else {
    showToast("食谱不存在");
    router.push("/recipe/list");
  }
});
</script>

<style scoped>
.recipe-detail-container {
  padding-bottom: 60px;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.nav-placeholder {
  height: 46px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.recipe-cover {
  position: relative;
  margin-bottom: 16px;
}

.recipe-actions {
  position: absolute;
  bottom: 16px;
  right: 16px;
  display: flex;
  gap: 12px;
}

.action-btn {
  width: 40px;
  height: 40px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.recipe-header {
  padding: 0 16px 16px;
  background-color: #fff;
  margin-bottom: 8px;
}

.recipe-title {
  font-size: 20px;
  font-weight: bold;
  margin: 12px 0 8px;
}

.recipe-rating {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.rating-count {
  font-size: 14px;
  color: #999;
}

.recipe-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #666;
}

.recipe-tags {
  margin-top: 12px;
}

.tab-content {
  padding: 16px;
  background-color: #fff;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 16px 0 8px;
  color: #333;
}

.servings,
.per-serving {
  font-size: 14px;
  font-weight: normal;
  color: #999;
}

.step-content {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.step-content p {
  flex: 1;
  margin: 0;
}

.pie-chart-placeholder {
  height: 200px;
  background-color: #f2f2f2;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  margin-bottom: 16px;
}

.comments-section {
  margin-top: 16px;
  padding: 16px;
  background-color: #fff;
}

.user-rating {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f2f2f2;
}

.rate-title {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.comment-item {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f2f2f2;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 8px;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
}

.related-recipes {
  margin-top: 16px;
  padding: 16px;
  background-color: #fff;
}

.recipes-scroll {
  display: flex;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
  padding-bottom: 8px;
}

.recipes-scroll::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.related-recipe-card {
  flex: 0 0 auto;
  width: 120px;
  margin-right: 12px;
}

.related-recipe-name {
  font-size: 12px;
  margin-top: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 8px 16px;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.review-form {
  padding: 16px;
}

.rating-area {
  margin-bottom: 16px;
}

.upload-area {
  margin-top: 16px;
}

.upload-title {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}
</style>
